﻿using ClosedXML.Excel;
using CommHelper;
using DocumentFormat.OpenXml.Spreadsheet;
using Newtonsoft.Json;
using NX5Web.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace NX5Web.Controllers
{
    public class ExcelController : ApiController
    {
        public class Lesson
        {
            public String LessonUUID { set; get; }
        }

        public class LessonSentence
        {
            public String SentenceEn { set; get; }
            public String SentenceCn { set; get; }

            public Int32 SentenceId { set; get; }

            private List<LessonWord> _Words = new List<LessonWord>();
            public List<LessonWord> Words
            {
                set { _Words = value; }
                get { return _Words; }
            }
        }

        public class LessonWord
        {
            public String Word { set; get; }
            public String Mean { set; get; }
            public String PS { set; get; }
            public String Syllable { set; get; }
            public Boolean NeedWrite { set; get; } 
            public Int32 LostLv { set; get; }
        }

        [HttpGet]
        public IHttpActionResult Test()
        {
            using (var workbook = new XLWorkbook())
            {
                // 添加一个工作表
                var worksheet = workbook.Worksheets.Add("Sample Sheet");

                // 添加一些数据
                worksheet.Cell(1, 1).Value = "Hello";
                worksheet.Cell(2, 1).Value = "World";
                worksheet.Cell(1, 2).Value = "Number";
                worksheet.Cell(2, 2).Value = 123;

                // 保存工作簿到文件
                workbook.SaveAs("E:\\Webs\\NX5\\UploadFiles\\download\\2025-09-15\\123.xlsx");
            }
            return null;
        }




        [HttpPost]
        public IHttpActionResult LessonResult(Lesson lesson)
        {
            DataTable dt = new DataTable();
            String Path = ConfigManager.GetAppSettings("SavePath") + "\\download\\LessonReports";
            String FileName = lesson.LessonUUID + ".xlsx";

            if (System.IO.File.Exists(Path + "\\" + FileName))
            {
                String Url = Path + "\\" + FileName;
                Url = Url.Replace(ConfigManager.GetAppSettings("SavePath"), "").Replace("\\", "/");
                ApiHttpRequest apiHttpRequest = new ApiHttpRequest
                {
                    status = true,
                    data = "/UploadFiles" + Url
                };
                return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, apiHttpRequest));
            }

            List<LessonSentence> Sentences = new List<LessonSentence>();

            if (!System.IO.Directory.Exists(Path))
            {
                System.IO.Directory.CreateDirectory(Path);
            }
            try
            {
                DataManager dm = new DataManager();
                dt = dm.Procedure("LessExcle", "[{\"UUID\":\"" + lesson.LessonUUID + "\"}]").table;
                String Title = "";
                String Time = "";
                String TeacherName = "";
                  

                if (dt.Rows.Count > 0)
                {
                    
                    foreach (DataRow dr in dt.Rows)
                    {
                        Title = dr["Title"].ToString();
                        Time = dr["StudyTime"].ToString();
                        TeacherName = dr["TeacherName"].ToString();

                        LessonSentence ls = Newtonsoft.Json.JsonConvert.DeserializeObject<LessonSentence>(dr["SentenceSnapshot"].ToString());
                        ls.SentenceId = Int32.Parse(dr["SentenceIDSnapshot"].ToString());
                        LessonWord Word = new LessonWord();
                        Word.LostLv = Int32.Parse(dr["LostLv"].ToString()) / 2;
                        Word.Word = dr["Word"].ToString();
                        Word.Mean = dr["Mean"].ToString();
                        Word.PS = dr["PS"].ToString();
                        Word.Syllable = dr["Syllable"].ToString();
                        Word.NeedWrite = Boolean.Parse(dr["NeedWrite"].ToString());

                        Boolean Exists = false;
                        foreach (LessonSentence l in Sentences)
                        {
                            if (l.SentenceId == ls.SentenceId)
                            {
                                Exists = true;
                                l.Words.Add(Word);
                                break;
                            }
                        }


                        if (!Exists)
                        {
                            ls.Words.Add(Word);
                            Sentences.Add(ls);
                        }
                    }


                    var RowIndex = 1;

                    using (var workbook = new XLWorkbook())
                    {
                        // 添加一个工作表
                        var worksheet = workbook.Worksheets.Add("课程内容");

                        worksheet.Range("A" + RowIndex + ":C" + RowIndex).Merge();
                        worksheet.Cell(RowIndex, 1).Value = Title;
                        //worksheet.Range("D" + RowIndex + ":E" + RowIndex).Merge();
                        worksheet.Cell(RowIndex, 4).Value = "老师";
                        worksheet.Cell(RowIndex, 5).Value = TeacherName;
                        worksheet.Cell(RowIndex, 6).Value = Time;
                        worksheet.Column(6).Width = 40;
                        RowIndex++;

                        foreach (LessonSentence l in Sentences)
                        {
                            worksheet.Cell(RowIndex, 1).Value = "英文句";
                            worksheet.Range("B" + RowIndex + ":F" + RowIndex).Merge();
                            worksheet.Cell(RowIndex, 2).Value = l.SentenceEn;
                            RowIndex++;
                            worksheet.Cell(RowIndex, 1).Value = "中文句";
                            worksheet.Range("B" + RowIndex + ":F" + RowIndex).Merge();
                            worksheet.Cell(RowIndex, 2).Value = l.SentenceCn;
                            RowIndex++;

                            worksheet.Cell(RowIndex, 1).Value = "单词";
                            worksheet.Cell(RowIndex, 2).Value = "意思";
                            worksheet.Cell(RowIndex, 3).Value = "音标";
                            worksheet.Cell(RowIndex, 4).Value = "音节";
                            worksheet.Cell(RowIndex, 5).Value = "必写";
                            worksheet.Cell(RowIndex, 6).Value = "陌生程度(1-9 数值越大越陌生)";
                            RowIndex++;

                            foreach (LessonWord word in l.Words)
                            {
                                worksheet.Cell(RowIndex, 1).Value = word.Word;
                                worksheet.Cell(RowIndex, 2).Value = word.Mean;
                                worksheet.Cell(RowIndex, 3).Value = word.PS;
                                worksheet.Cell(RowIndex, 4).Value = word.Syllable;
                                worksheet.Cell(RowIndex, 5).Value = (word.NeedWrite ? "是" : "否");
                                worksheet.Cell(RowIndex, 6).Value = (word.LostLv == 0 ? "熟悉" : word.LostLv.ToString() + "级");
                                RowIndex++;
                            }

                            RowIndex++;
                        }

                        var range = worksheet.Range("A1:F" + RowIndex);
                        range.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                        range.Style.Border.TopBorder = XLBorderStyleValues.Thin;
                        range.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                        range.Style.Border.RightBorder = XLBorderStyleValues.Thin;
                        range.Style.Border.InsideBorder = XLBorderStyleValues.Thin;

                        

                        // 保存工作簿到文件
                        workbook.SaveAs(Path + "\\" + FileName);
                        //workbook.SaveAs("e:\\xx.xlsx");
                    }
                }
            }
            catch (Exception ex)
            { 
                ApiHttpRequest ErrorHttpRequest = new ApiHttpRequest
                {
                    status = false,
                    data = "获取失败." + ex.ToString()
                };
                return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, ErrorHttpRequest));
            }

            if (dt.Rows.Count > 0)
            {
                String Url = Path + "\\" + FileName;
                Url = Url.Replace(ConfigManager.GetAppSettings("SavePath"), "").Replace("\\", "/");
                ApiHttpRequest apiHttpRequest = new ApiHttpRequest
                {
                    status = true,
                    data = "/UploadFiles" + Url
                };
                return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, apiHttpRequest));
            }
            else
            {
                ApiHttpRequest apiHttpRequest = new ApiHttpRequest
                {
                    status = false,
                    data = "没有学习内容"
                };
                return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, apiHttpRequest));
            }
        }
    }
}